<script setup>
import {onMounted, reactive, ref} from 'vue'
import {ElMessage} from 'element-plus'
import http from '@/request/http.js'

// 积分概览数据
const totalPoints = ref(0)
const levelName = ref('LV1 新手')
const monthEarned = ref(0)
const monthSpent = ref(0)

// 明细列表数据
const detailList = ref([])
const filterReason = ref('')
const reasonOptions = ref([
  {code: 'ARTICLE_PUBLISH', name: '发布文章'},
  {code: 'ARTICLE_REPLY', name: '回复评论'},
  {code: 'ARTICLE_LIKE', name: '点赞'},
  {code: 'ARTICLE_POINTS', name: '分享文章'},
  {code: 'SYSTEM_REWARD', name: '系统奖励'},
  {code: 'EXCHANGE_GOODS', name: '兑换商品'},
  {code: 'SIGN_DAILY', name: '每日签到'},
  {code: 'SIGN_CONTINUOUS_7', name: '连续7天签到'},
  {code: 'SIGN_CONTINUOUS_30', name: '连续30天签到'}
])

// 分页参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})
const availablePoints = ref(0)
const levelData = ref({
  currentLevel: {
    levelId: 1,
    levelName: 'LV1 新手'
  },
  nextLevel: null,
  progress: 0
})
// 获取积分概览信息（实际接口调用）
const fetchPointsInfo = async () => {
  try {
    const levelData = ref({
      currentLevel: {
        levelId: 1,
        levelName: 'LV1 新手'
      },
      nextLevel: null,
      progress: 0
    })
    const response = await http.get('/points/info')
    if (response.code === 200) {
      const data = response.data
      totalPoints.value = data.totalPoints || 0
      availablePoints.value = data.availablePoints || 0
      levelName.value = data.levelName || 'LV1 新手'
    } else {
      ElMessage.error(response.msg || '获取积分信息失败')
    }
  } catch (error) {
    console.error('获取积分信息异常：', error)
    ElMessage.error('获取积分信息失败，请稍后重试')
  }
}
//获取等级
const fetchRealTimeLevel = async () => {
  try {
    const response = await http.get('/points/level/info')
    if (response.code === 200) {
      const resData = response.data?.data || response.data || {}
      // 更新等级数据
      levelData.value = {
        currentLevel: resData.currentLevel || {levelId: 1, levelName: 'LV1 新手'},
        nextLevel: resData.nextLevel || null,
        progress: Number(resData.progress || 0)
      }
      levelName.value = levelData.value.currentLevel.levelName
    } else {
      ElMessage.error(response.msg || '获取等级信息失败')
    }
  } catch (error) {
    console.error('获取实时等级异常：', error)
    ElMessage.error('获取等级信息失败，请稍后重试')
  }
}
// 获取积分明细
const fetchPointsDetail = async () => {
  try {
    const params = {
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize,
      reasonCode: filterReason.value || undefined
    }

    const response = await http.get('/points/detail', {params})
    if (response.code === 200) {
      detailList.value = response.data.records || []
      pagination.total = response.data.total || 0
      await fetchPointsInfo()
      // 明细更新后，同步刷新实时等级
      await fetchRealTimeLevel()
    } else {
      ElMessage.error(response.msg || '获取积分明细失败')
    }
  } catch (error) {
    console.error('获取积分明细异常：', error)
    ElMessage.error('获取积分明细失败，请稍后重试')
  }
}
// 新增获取月度统计的方法
const fetchMonthSummary = async () => {
  try {
    const response = await http.get('/points/month-summary')
    if (response.code === 200) {
      monthEarned.value = response.data.monthEarned || 0
      monthSpent.value = response.data.monthSpent || 0
    }
  } catch (error) {
    console.error('获取月度积分统计失败：', error)
    ElMessage.error('获取月度统计失败')
  }
}

// 计算本月获得积分
const calculateMonthEarned = () => {
  const now = new Date();
  const currentMonth = now.getMonth();
  const currentYear = now.getFullYear();

  return detailList.value
      .filter(item => {
        const itemDate = new Date(item.createTime);
        return itemDate.getMonth() === currentMonth &&
            itemDate.getFullYear() === currentYear &&
            item.pointsChange > 0;
      })
      .reduce((sum, item) => sum + item.pointsChange, 0);
};

// 计算本月消耗积分
const calculateMonthSpent = () => {
  const now = new Date();
  const currentMonth = now.getMonth();
  const currentYear = now.getFullYear();

  return Math.abs(detailList.value
      .filter(item => {
        const itemDate = new Date(item.createTime);
        return itemDate.getMonth() === currentMonth &&
            itemDate.getFullYear() === currentYear &&
            item.pointsChange < 0;
      })
      .reduce((sum, item) => sum + item.pointsChange, 0));
};

// 筛选条件变化
const handleFilterChange = () => {
  pagination.currentPage = 1
  fetchPointsDetail()
}

// 分页事件处理（与GoodsManagement保持一致）
const handleSizeChange = (val) => {
  pagination.pageSize = val
  pagination.currentPage = 1
  fetchPointsDetail()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchPointsDetail()
}

// 格式化日期时间
const formatDateTime = (row, column, cellValue) => {
  if (!cellValue) return ''
  return new Date(cellValue).toLocaleString()
}

// 页面加载时初始化数据
onMounted(() => {
  fetchPointsInfo()
  fetchRealTimeLevel()
  fetchPointsDetail()
  fetchMonthSummary()
})
</script>

<template>
  <div class="points-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>我的积分</h1>
    </div>

    <!-- 积分概览卡片 -->
    <el-row :gutter="20" class="points-overview">
      <el-col :span="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-item">
            <p class="stat-label">积分等级</p>
            <p class="stat-value">{{ levelName }}</p>
          </div>
        </el-card>
      </el-col>
      <!--            <el-col :span="6">-->
      <!--              <el-card class="stat-card" shadow="hover">-->
      <!--                <div class="stat-item">-->
      <!--                  <p class="stat-label">当前总积分</p>-->
      <!--                  <p class="stat-value">{{ totalPoints }}</p>-->
      <!--                </div>-->
      <!--              </el-card>-->
      <!--            </el-col>-->
      <el-col :span="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-item ">
            <p class="stat-label">积分</p>
            <p class="text-blue-400 text-2xl font-bold">{{ availablePoints }}</p>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-item">
            <p class="stat-label">本月获得</p>
            <p class="stat-value text-success">{{ monthEarned }}</p>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-item">
            <p class="stat-label">本月消耗</p>
            <p class="stat-value text-danger">{{ monthSpent }}</p>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 积分明细区域 -->
    <el-card class="points-detail-card" shadow="hover">
      <div class="detail-header">
        <h2>积分明细记录</h2>
        <el-select
            v-model="filterReason"
            clearable
            placeholder="筛选原因"
            style="width: 200px;"
            @change="handleFilterChange"
        >
          <el-option
              v-for="reason in reasonOptions"
              :key="reason.code"
              :label="reason.name"
              :value="reason.code"
          ></el-option>
        </el-select>
      </div>

      <el-table
          :data="detailList"
          border
          style="width: 100%; margin-top: 15px;"
      >
        <el-table-column
            :formatter="formatDateTime"
            label="变动时间"
            prop="createTime"
            width="200"
        ></el-table-column>
        <el-table-column
            label="变动原因"
            prop="reasonName"
            width="200"
        ></el-table-column>
        <el-table-column
            label="积分变动"
            prop="pointsChange"
            width="150"
        >
          <template #default="scope">
            <span :class="scope.row.pointsChange > 0 ? 'text-success' : 'text-danger'">
              {{ scope.row.pointsChange > 0 ? '+' : '' }}{{ scope.row.pointsChange }}
            </span>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页控件 -->
      <el-pagination
          :current-page="pagination.currentPage"
          :page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          style="margin-top: 15px; text-align: right;"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      ></el-pagination>
    </el-card>
  </div>

</template>


<style scoped>
.points-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.page-header {
  margin-bottom: 20px;
}

.page-header h1 {
  font-size: 24px;
  color: #1f2329;
  margin: 0;
}

.points-overview {
  margin-bottom: 20px;
}

.stat-card {
  height: 100%;
}

.stat-item {
  text-align: center;
  padding: 15px 0;
}

.stat-label {
  color: #606266;
  font-size: 14px;
  margin-bottom: 10px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.points-detail-card {
  padding: 20px;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.detail-header h2 {
  font-size: 18px;
  margin: 0;
  color: #1f2329;
}

.text-success {
  color: #67c23a;
}

.text-danger {
  color: #f56c6c;
}
</style>